package com.typing.battle.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;

import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.typing.battle.R;
import com.typing.battle.database.FriendManager;
import com.typing.battle.value.FriendDTO;
import com.typing.battle.view.FriendListViewForChatRoom;
import com.typing.battle.view.FriendListViewForDefault;

public class TypingBattleFriendListActivity extends Activity {
	/** Called when the activity is first created. */
	private LinearLayout layout,progressLayout;
	private Button searchBtn;
	private EditText searchText;
	private RelativeLayout relLayout;
	private FriendListViewForDefault vList;
	private FriendListViewForChatRoom vListChat;
	private Context mContext;
	private Button add, edit;
	private FriendManager manager;

	public static final String PARAMETER_NAME = "PARAMETER";
	public static final int TYPE_DEFAULT = 0;
	public static final int TYPE_CHATROOM = 1;
	
	public static final int CONTACT_PICKER = 0;
	private int type;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		mContext = this;
		
		type = getIntent().getIntExtra(PARAMETER_NAME, 0);
		switch (type) {
		case TYPE_DEFAULT:
			vList = new FriendListViewForDefault(this);
			setContentView(R.layout.battle_friend_list);
			progressLayout = (LinearLayout) View.inflate(this, R.layout.battle_list_progress, null);
	    	progressLayout.setVisibility(View.INVISIBLE);
	    	vList.addFooterView(progressLayout);
	    	vList.setOnScrollListener(new OnScrollListener() {
		
				// @Override
				public void onScrollStateChanged(AbsListView view, int scrollState) {
					// TODO Auto-generated method stub
					
				}
				
				// @Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					// TODO Auto-generated method stub
					
					if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
						Log.v("list", "IN, totalItemCount = " + totalItemCount);
						
						if (vList.getTotalCount() > vList.getCurrentIndex()) {
							progressLayout.setVisibility(View.VISIBLE);
							vList.getNextList();
						} else {
							progressLayout.setVisibility(View.INVISIBLE);
						}
						
					}
				}
			});        
			/*add = (Button) findViewById(R.id.btn_add_friend);
			edit = (Button) findViewById(R.id.btn_edit_friend);

			add.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent i = new Intent(Intent.ACTION_PICK);
					i.setData(Uri
							.parse("content://com.android.contacts/data/phones"));
					startActivityForResult(i, CONTACT_PICKER);
				}

			});

			edit.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

				}

			});*/
	    	searchText = (EditText)findViewById(R.id.input_search_friend);
	    	searchBtn = (Button)findViewById(R.id.btn_search);
	    	searchBtn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					vList.searchFriend(searchText.getText().toString());
				}
	    		
	    	});
	    	relLayout = (RelativeLayout) findViewById(R.id.layout_friend_list_rel);
	    	layout = (LinearLayout)relLayout.findViewById(R.id.layout_friend_list);
			manager = new FriendManager(this);
			layout.addView(vList, new LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT));
			break;
		case TYPE_CHATROOM:
			//vList = new FriendListViewForChatRoom(this);
			//setContentView(R.layout.battle_friend_list_sub);
			
			vListChat = new FriendListViewForChatRoom(this);
			setContentView(R.layout.battle_friend_list_sub);
			progressLayout = (LinearLayout) View.inflate(this, R.layout.battle_list_progress, null);
	    	progressLayout.setVisibility(View.INVISIBLE);
	    	vListChat.addFooterView(progressLayout);
	    	vListChat.setOnScrollListener(new OnScrollListener() {
		
				// @Override
				public void onScrollStateChanged(AbsListView view, int scrollState) {
					// TODO Auto-generated method stub
					
				}
				
				// @Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					// TODO Auto-generated method stub
					
					if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
						Log.v("list", "IN, totalItemCount = " + totalItemCount);
						
						if (vListChat.getTotalCount() > vListChat.getCurrentIndex()) {
							progressLayout.setVisibility(View.VISIBLE);
							vListChat.getNextList();
						} else {
							progressLayout.setVisibility(View.INVISIBLE);
						}
						
					}
				}
			});        
			/*add = (Button) findViewById(R.id.btn_add_friend);
			edit = (Button) findViewById(R.id.btn_edit_friend);

			add.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent i = new Intent(Intent.ACTION_PICK);
					i.setData(Uri
							.parse("content://com.android.contacts/data/phones"));
					startActivityForResult(i, CONTACT_PICKER);
				}

			});

			edit.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

				}

			});*/
	    	layout = (LinearLayout) findViewById(R.id.layout_friend_list);
			manager = new FriendManager(this);
			layout.addView(vListChat, new LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT));
			break;
		}
		
	}
/*
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) { 
        case CONTACT_PICKER:   
            // If the operation succeeded 
            if (resultCode == Activity.RESULT_OK) { 
                String phoneNum = "";
                String name = "";
                // A StringBuilder used to build the String 
                // that we will display in our TextView 
                StringBuilder sb = new StringBuilder(); 
                  
                // Get the Uri for the data returned by the contact picker 
                // This Uri identifies the person picked 
                Uri contactData = data.getData(); 
                  
                // Query the table 
                Cursor contactsCursor = managedQuery(contactData, 
                        null, null, null, null); 
  
                // If the cursor is not empty 
                if (contactsCursor.moveToFirst()) { 
                      
                    // Get the id name and phone number indicator 
                    String id = contactsCursor.getString(contactsCursor 
                            .getColumnIndexOrThrow(ContactsContract.Contacts._ID)); 
                    name = contactsCursor.getString(contactsCursor 
                            .getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
                    
                    // Build the Uri to query to table 
                    Uri myPhoneUri = Uri.withAppendedPath( 
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, id); 
                      
                    // Query the table 
                    Cursor phoneCursor = managedQuery( 
                            myPhoneUri, null, null, null, null); 
  
                        // Get the phone numbers from the contact 
                    for (phoneCursor.moveToFirst(); !phoneCursor.isAfterLast(); phoneCursor.moveToNext()) { 
                          
                        // Get a phone number 
                        phoneNum = phoneCursor.getString(phoneCursor 
                                .getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));                    
                        
                    } 
                    
  
                    // Set the text in our TextView to display what we got 
                    Log.d("num ",""+phoneNum);	
                    Log.d("name ",""+name);	
                    
                    FriendDTO friend = new FriendDTO();
					friend.setFriendName(name);
					friend.setFriendPhoneNo(phoneNum);
					friend.setBlockYn("N");
					manager.open();
					manager.addFriend(friend);
					manager.close();
					
					((FriendListViewForDefault)vList).RefreshData();
                } 
            } 
            break; 
        } 		
			
	}
*/
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("resultCode",resultCode+"");
		switch (requestCode) { 
        case CONTACT_PICKER: 
        	if (data != null) { 
	            FriendDTO friend = new FriendDTO();
				friend.setFriendEmail(data.getStringExtra("friendEmail"));
				friend.setFriendPhoneNo(data.getStringExtra("friendPhoneNo"));
				friend.setFriendName(data.getStringExtra("friendName"));
				friend.setBlockYn("N");
				manager.open();
				manager.addFriend(friend);
				manager.close();
				
				((FriendListViewForDefault)vList).RefreshData();
	            break; 
        	}
        } 		
			
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		switch (type) {
			case TYPE_DEFAULT:
				menu.add("친구추가");
				menu.add("편집");
				break;
			case TYPE_CHATROOM:
				break;
		}
		return super.onCreateOptionsMenu(menu);
	}
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
    	switch (type) {
		case TYPE_DEFAULT:
			if(item.getTitle().equals("친구추가")){
	    		/*Intent i = new Intent(Intent.ACTION_PICK);
				i.setData(Uri
						.parse("content://com.android.contacts/data/phones"));
				startActivityForResult(i, CONTACT_PICKER);*/
				Intent intent = new Intent(this,TypingBattleFriendAddActivity.class);
				startActivityForResult(intent,CONTACT_PICKER);
	    	}else if(item.getTitle().equals("편집")){
	    		
	    	}		
			break;
		case TYPE_CHATROOM:
			break;
    	}    	
		return super.onOptionsItemSelected(item);
	}
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	switch (type) {
		case TYPE_DEFAULT:
			vList.RefreshData();	
			break;
		case TYPE_CHATROOM:
			vListChat.RefreshData();
			break;
    	}    	
    	
    	super.onResume();
    }
}
